<template>
  <div class="inner-container">
    <!-- 查询条件 -->
    <div class="x-header">
      <span class="navTitle">企业人员查询</span>
      <el-divider></el-divider>
      <el-form label-width="90px" ref="formSearch" :model="formSearch">
        <el-row>
          <el-col :span="8">
            <el-form-item label="用户名 :" prop="username">
              <el-input placeholder="请输入人员姓名" v-model="formSearch.username"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="人员姓名 :" prop="name">
              <el-input placeholder="请输入人员姓名" v-model="formSearch.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号 :" prop="identityNum">
              <el-input placeholder="请输入身份证号" v-model="formSearch.identityNum"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="人员类型 :" prop="position">
              <el-select style="width:100%" v-model="formSearch.position">
                <el-option
                  v-for="(item,index) in personTypes"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-button
              type="primary"
              style="margin-left:90px"
              icon="el-icon-search"
              @click="handleQueryData"
            >查询</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset('formSearch')">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 企业列表 -->
    <div class="x-record_list">
      <div class="navTitle">企业人员列表</div>
      <el-divider></el-divider>
      <div class="btn_list">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddEnterprise">新增</el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          @click="handleBatchDelete"
          :disabled="multipleData.length == 0"
        >批量删除</el-button>
      </div>
      <el-table
        :data="tableData"
        style="width:100%;min-height:150px"
        v-loading="isLoadingTable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column type="index" width="55" align="center"></el-table-column>
        <el-table-column label="用户名" prop="username" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="姓名" prop="name" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="性别" prop="gender" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="身份证号" prop="num" align="center"></el-table-column>
        <!-- <el-table-column label="人员类型" prop="uniformSocialCreditCode" align="center"></el-table-column> -->
        <el-table-column label="职位/职务" prop="position" align="center"></el-table-column>
        <el-table-column label="联系方式" prop="mobilePhone" align="center"></el-table-column>
        <el-table-column label="所属企业" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.enterprise">{{ scope.row.enterprise.name }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="注册类别" prop="contactName" align="center"></el-table-column> -->
        <!-- <el-table-column label="毕业院校" prop="graduateSchool" align="center"></el-table-column>
        <el-table-column label="毕业专业" prop="graduateSpecialty" align="center"></el-table-column>-->
        <el-table-column label="操作" align="center" width="250">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleDetail(scope.row)"
              v-loading.fullscreen.lock="loadingDetail"
            >详情</el-button>
            <el-button
              type="primary"
              size="mini"
              @click="handleEdite(scope.row)"
              v-loading.fullscreen.lock="loadingEdite"
            >编辑</el-button>
            <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="text-center">
        <el-pagination
          :current-page.sync="currentPage"
          :page-size="10"
          layout="prev, pager, next, jumper"
          :total="total"
          style="margin-top:20px"
          @current-change="handleCurrentPage"
        ></el-pagination>
      </div>
    </div>
    <!-- 新增弹框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="dialogTitle"
      :visible.sync="personDialogVisible"
      style="margin: 10vh 0;"
      top="0"
      @close="handleCloseDialog('personForm')"
    >
      <div>
        <el-form
          label-position="top"
          :model="dialogFormData"
          ref="personForm"
          :rules="enterpriceFormRules"
        >
          <el-row>
            <el-col :span="12" class="px-1">
              <el-form-item label="用户名 :" prop="username">
                <el-input
                  placeholder="请输入用户名"
                  v-model="dialogFormData.username"
                  :readonly="isReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1" v-if="submitType == 0">
              <el-form-item label="密码 :" prop="password">
                <el-input
                  placeholder="请输入密码"
                  v-model="dialogFormData.password"
                  :readonly="isReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1" v-if="submitType == 1">
              <el-form-item label="重置密码 :">
                <el-input
                  placeholder="请输入密码"
                  v-model="dialogFormData.password"
                  :readonly="isReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="人员姓名 :" prop="name">
                <el-input
                  placeholder="请输入人员姓名"
                  v-model="dialogFormData.name"
                  :readonly="isReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="身份证号码 :" prop="num">
                <el-input
                  placeholder="请输入身份证号码"
                  v-model="dialogFormData.num"
                  :readonly="isReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="联系电话 :" prop="mobilePhone">
                <el-input
                  placeholder="请输入联系电话"
                  v-model="dialogFormData.mobilePhone"
                  type="number"
                  :readonly="isReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12" class="px-1">
							<el-form-item label="职务/职位 :" prop="position">
								<el-input placeholder="请输入职务/职位" v-model="dialogFormData.position" :readonly="isReadonly"></el-input>
							</el-form-item>
            </el-col>-->
            <el-col :span="12" class="px-1">
              <el-form-item label="毕业院校 :" prop="graduateSchool">
                <el-input
                  placeholder="请输入毕业院校"
                  v-model="dialogFormData.graduateSchool"
                  :readonly="isReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="毕业专业 :" prop="graduateSpecialty">
                <el-input
                  placeholder="请输入毕业专业"
                  v-model="dialogFormData.graduateSpecialty"
                  :readonly="isReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12" class="px-1">
              <el-form-item
                label="行政等级"
                prop="regionPermission"
                v-show="submitType == 0 || isEdite"
              >
                <el-cascader
                  v-model="dialogFormData.regionPermission"
                  style="width:100%"
                  :props="defaultPropsDistrict"
                  ref="district"
                  @change="handelSelectDistrict"
                ></el-cascader>
              </el-form-item>
              <el-form-item
                label="行政等级"
                v-show="submitType == 1 && !isEdite"
                prop="regionPermission"
              >
                <el-input v-model="dialogFormData.regionName" :readonly="true" style="width:100%">
                  <el-button slot="append" @click="handleChangeEdite" icon="el-icon-edit"></el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="行政等级" v-show="submitType == 2" prop="regionPermission">
                <el-input v-model="dialogFormData.regionName" :readonly="true" style="width:100%"></el-input>
              </el-form-item>
            </el-col>-->
            <el-col :span="12" class="px-1">
              <el-form-item label="所属企业 :" prop="enterpriseId">
                <el-select
                  style="width:100%"
                  v-model="dialogFormData.enterpriseId"
                  filterable
                  :disabled="isReadonly"
                >
                  <el-option
                    v-for="(item,index) in enterpriseList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="职务/职位 :" prop="position">
                <el-select
                  style="width:100%"
                  v-model="dialogFormData.position"
                  :disabled="isReadonly"
                >
                  <el-option
                    v-for="(item,index) in personTypes"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="性别 :" prop="gender">
                <el-radio-group v-model="dialogFormData.gender" :readonly="isReadonly">
                  <el-radio-button label="MAN">男</el-radio-button>
                  <el-radio-button label="FEMALE">女</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" style="text-align: center;" v-show="submitType != 2">
        <el-button type="primary" @click="handleSubmit('personForm')">确定</el-button>
        <el-button @click="handleReset('personForm')">重置</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCompanyPersonTable,
  getCompanyTable,
  newAddEnterPrisePerson,
  getPersonDetailByID,
  getDeletePersonByID,
  editeEnterPrisePerson,
  getBatchDeletePersonByID,
  getOrganizationDistrict
} from '@/api/project/integrity/person'
import moment from 'moment'
export default {
  data() {
    return {
      //查询条件
      formSearch: {
        name: '',
        identityNum: '',
        position: '',
        username: ''
      },
      //表格
      isLoadingTable: false,
      tableData: [],
      //分页
      currentPage: 1,
      total: 0,
      //弹框参数
      dialogTitle: '人员管理-新增',
      personDialogVisible: false,
      //r人员类型
      personTypes: [
        { name: '项目负责人', value: '项目负责人' },
        { name: '项目经理', value: '项目经理' },
        { name: '技术负责人', value: '技术负责人' },
        { name: '一般技术员', value: '一般技术员' },
        { name: '施工员', value: '施工员' },
        { name: '安全员', value: '安全员' },
        { name: '材料员', value: '材料员' },
        { name: '质检员', value: '质检员' },
        { name: '造价员', value: '造价员' }
      ],
      //新增、编辑参数
      dialogFormData: {
        username: '',
        password: '',
        name: '',
        gender: 'MAN',
        num: '',
        mobilePhone: '',
        position: '',
        graduateSchool: '',
        graduateSpecialty: '',
        enterpriseId: ''
        // regionPermission: '',
        // regionName: ''
      },
      organizationDistrict: [],
      loadingDetail: false,
      loadingEdite: false,
      //新增、编辑类型判断
      submitType: 0, //0:新增，1:编辑，2:详情
      isEdite: false,
      //表单验证规则
      enterpriceFormRules: {
        username: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        password: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        name: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        gender: [{ required: true, message: '不能为空！', trigger: 'change' }],
        num: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        mobilePhone: [
          { required: true, message: '不能为空！', trigger: 'blur' }
        ],
        // graduateSchool: [
        //   { required: true, message: '不能为空！', trigger: 'blur' }
        // ],
        position: [
          { required: true, message: '不能为空！', trigger: 'change' }
        ],
        // graduateSpecialty: [
        //   { required: true, message: '不能为空！', trigger: 'blur' }
        // ],
        enterpriseId: [
          { required: true, message: '不能为空！', trigger: 'change' }
        ]
        // regionPermission: [
        //   { required: true, message: '请选择！', trigger: 'change' }
        // ]
      },
      //查询企业列表
      enterpriseList: [],
      isReadonly: false,
      //多选数据
      multipleData: [],
      defaultPropsDistrict: {
        lazy: true,
        checkStrictly: false,
        lazyLoad(node, resolve) {
          const { level, value } = node
          getOrganizationDistrict({ parentId: value }).then(res => {
            const nodes = res.data.map(item => ({
              value: item.id,
              label: item.name,
              leaf: level >= 3
            }))
            resolve(nodes)
          })
        }
      }
    }
  },
  methods: {
    getInitTableData: function() {
      this.handleGetTableData()
      this.handleEnterpriseData()
      this.getOrganizationDistrict(1)
    },
    //获取企业人员列表数据
    handleGetTableData: function(page) {
      this.isLoadingTable = true
      page ? (this.currentPage = page) : ''
      let params = {
        page: this.currentPage,
        size: 10
      }
      params = Object.assign(params, this.formSearch)
      getCompanyPersonTable(params).then(res => {
        this.isLoadingTable = false
        this.tableData = res.data.rows
        this.total = res.data.total
      })
    },
    //查询企业列表
    handleEnterpriseData: function(id) {
      return new Promise((resolve, reject) => {
        let params = {
          page: 1,
          size: 9999
        }
        getCompanyTable(params).then(res => {
          this.enterpriseList = res.data.rows
          resolve()
        })
      })
    },
    //获取组织区域列表
    getOrganizationDistrict: function(id) {
      getOrganizationDistrict({ parentId: id }).then(res => {
        this.organizationDistrict = res.data
      })
    },
    //区域权限修改
    handleChangeEdite: function() {
      this.isEdite = true
    },
    //区域选择回调
    handelSelectDistrict: function(val) {
      this.dialogFormData['cityId'] = ''
      this.dialogFormData['districtId'] = ''
      this.dialogFormData['townId'] = ''
      this.dialogFormData['villageId'] = ''
      if (val) {
        val[0] && (this.dialogFormData['cityId'] = val[0])
        val[1] && (this.dialogFormData['districtId'] = val[1])
        val[2] && (this.dialogFormData['townId'] = val[2])
        val[3] && (this.dialogFormData['villageId'] = val[3])
      }
    },
    //根据ID查询人员信息
    handlePersonDetailByID: function(id) {
      return new Promise((reject, resolve) => {
        let params = {
          id: id
        }
        getPersonDetailByID(params).then(res => {
          let obj = res.data
          var { name: city, id: cityId } = obj.city ? obj.city : {}
          var { name: district, id: districtId } = obj.district
            ? obj.district
            : {}
          var { name: town, id: townId } = obj.town ? obj.town : {}
          var { name: village, id: villageId } = obj.village ? obj.village : {}
          //   obj['regionName'] = [city, district, town, village]
          //     .filter(item => {
          //       return Boolean(item)
          //     })
          //     .join('/')
          //   obj['regionPermission'] = [
          //     cityId,
          //     districtId,
          //     townId,
          //     villageId
          //   ].filter(item => {
          //     return Boolean(item)
          //   })
          this.dialogFormData = obj
          this.dialogFormData['enterpriseId'] = obj['enterprise'].id
          reject()
        })
      })
    },
    //查询
    handleQueryData: function() {
      this.handleGetTableData(1)
    },
    //重置
    handleReset: function(formName) {
      this.$refs[formName].resetFields()
    },
    //新增企业
    handleAddEnterprise: function() {
      this.personDialogVisible = true
      this.dialogTitle = '人员管理-新增'
      this.submitType = 0
    },
    //新增、编辑
    handleSubmit: function(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.submitType == 0) {
            newAddEnterPrisePerson(this.dialogFormData).then(res => {
              this.$message.success('操作成功！')
              this.personDialogVisible = false
              this.handleGetTableData(1)
            })
          } else {
            console.log(this.dialogFormData, 222)
            editeEnterPrisePerson(this.dialogFormData).then(res => {
              this.$message.success('操作成功！')
              this.personDialogVisible = false
              this.handleGetTableData()
            })
          }
        }
      })
    },
    //弹框关闭回调
    handleCloseDialog: function(formName) {
      this.dialogFormData = {
        username: '',
        password: '',
        name: '',
        gender: 'MAN',
        type: '',
        num: '',
        mobilePhone: '',
        position: '',
        graduateSchool: '',
        graduateSpecialty: '',
        enterpriseId: ''
      }
      this.$refs[formName].resetFields()
      this.isReadonly = false
      this.isEdite = false
    },
    //批量删除
    handleBatchDelete: function() {
      this.$confirm('此操作将批量删除人员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(res => {
        let ids = this.multipleData
          .map(item => {
            return item.userId
          })
          .join(',')
        getBatchDeletePersonByID({ ids }).then(res => {
          this.$message.success('操作成功！')
          this.handleGetTableData()
        })
      })
    },
    //详细
    handleDetail: async function(row) {
      this.submitType = 2
      this.isReadonly = true
      this.dialogTitle = '人员管理-基本信息'
      this.loadingDetail = true
      await this.handlePersonDetailByID(row.userId)
      this.loadingDetail = false
      this.personDialogVisible = true
    },
    //编辑
    handleEdite: async function(row) {
      this.submitType = 1
      this.dialogTitle = '人员管理-编辑'
      this.loadingEdite = true
      await this.handlePersonDetailByID(row.userId)
      this.loadingEdite = false
      this.personDialogVisible = true
    },
    //单个删除
    handleDelete: function(row) {
      this.$confirm('此操作将删除该企业人员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(res => {
        getDeletePersonByID({ id: row.userId }).then(res => {
          this.$message.success('操作成功！')
          this.handleGetTableData()
        })
      })
    },
    //分页查询
    handleCurrentPage: function(page) {
      this.handleGetTableData(page)
    },
    //下拉选择强制刷新
    changeSelect: function() {
      this.$forceUpdate()
    },
    //多选回调
    handleSelectionChange: function(val) {
      this.multipleData = val
    }
  },
  created() {
    this.getInitTableData()
  }
}
</script>

<style lang="scss" scoped>
.inner-container {
  padding: 20px 30px;
  background-color: #fff;
  .x-header {
    .navTitle {
      font-size: 17px;
      font-weight: bold;
      font-family: PingFangSC-Regular;
      color: rgba(72, 73, 77, 1);
      margin-bottom: 20px;
    }
  }
  .x-record_list {
    .navTitle {
      font-size: 17px;
      font-weight: bold;
      font-family: PingFangSC-Regular;
      color: rgba(72, 73, 77, 1);
      margin: 20px 0;
    }
    .btn_list {
      // text-align: right;
      margin-bottom: 20px;
    }
  }
}
.px-1 {
  padding: 0 10px;
}
</style>
